package ch.csp.transformer;

import java.util.ArrayList;

import ch.csp.exchange.LineInfo;
import ch.csp.exchange.ParagraphWithLineAndWords;
import ch.csp.exchange.ParagraphWithLines;
import ch.csp.exchange.Words;

public class JustifyTransformer {
	
	//Teil Curdin: Bitte schreibe die tranform()-Funktion
	

	private final ArrayList<ParagraphWithLineAndWords> listOfParagraphWithLineAndWords;

	public JustifyTransformer(ArrayList<ParagraphWithLineAndWords> paragraphWithLineAndWords) {
		this.listOfParagraphWithLineAndWords = paragraphWithLineAndWords;
	}
	
	public ArrayList<ParagraphWithLines> transform(){
		ArrayList<ParagraphWithLines> listOfParagraphWithLines = new ArrayList<ParagraphWithLines>();
		
		// For each paragraph in list of paragraphs
		for(ParagraphWithLineAndWords p : listOfParagraphWithLineAndWords){
			ParagraphWithLines paragraph = new ParagraphWithLines();
			
			// Center each line
			for(LineInfo li : p.lineInfos){
				String centeredLine = centerAndFillUpLine(li);
				// Add centered line to new paragraph object
				paragraph.lines.add(centeredLine);
			}
			
			// Add new paragraph object to new list of paragraphs
			listOfParagraphWithLines.add(paragraph);
		}
		return listOfParagraphWithLines;
	}
	
	private String centerAndFillUpLine(LineInfo li){
		int additionalSpaces = li.additionalSpaces;
		Words words = li.words;
		
		if(words == null || words.size() < 1)
		{
			System.out.println("Error: Line without word");
			return "";
		}
		
		// If the line contains only one word
		if(words.size() < 2){
			String oneWordLine = "";
			oneWordLine += words.get(0);
			oneWordLine += getXSpaces(li.additionalSpaces);
			return oneWordLine;
			
		}
		
		// If the line contains more than one words
		int div = words.size() - 1;
		int spacesPerWord = additionalSpaces / div;
		int rest = additionalSpaces % div;
		String line = "";
		
		for(int i = 0; i < (words.size()-1); i++){
			if(rest != 0){
				line += words.get(i).concat(getXSpaces(spacesPerWord+1));
				rest--;
			}
			else{
				line += words.get(i).concat(getXSpaces(spacesPerWord));
			}
		}
		line += words.get(words.size()-1);
		return line;
	}
	
	private String getXSpaces(int count){
		String spaces = "";
		for(int i = 0; i < count; i++){
			spaces+=" ";
		}
		return spaces;
	}
}
